package com.probox.modules.controller.finance;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageInfo;
import com.probox.common.core.constant.HttpStatus;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.poi.ExcelUtil;
import com.probox.common.core.web.controller.BaseController;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.core.web.page.TableDataInfo;
import com.probox.common.entity.domain.customer.CustomerFundStore;
import com.probox.common.entity.domain.customer.CustomerInfo;
import com.probox.common.entity.domain.order.OrderExport;
import com.probox.common.entity.domain.order.OrderInfo;
import com.probox.common.entity.domain.order.OrderRecharge;
import com.probox.common.entity.domain.order.SaleExport;
import com.probox.common.entity.domain.platfom.PlatformStoreGroup;
import com.probox.common.entity.service.customer.ICustomerFundStoreService;
import com.probox.common.entity.service.customer.ICustomerInfoService;
import com.probox.common.entity.service.order.IOrderInfoService;
import com.probox.common.entity.service.order.IOrderRechargeService;
import com.probox.common.entity.service.platfom.IPlatformStoreGroupService;
import com.probox.common.entity.service.platfom.impl.StatisticsService;
import com.probox.common.entity.service.system.ISysUserService;
import com.probox.common.entity.vo.recharge.RechargeVo;
import com.probox.common.entity.vo.statistics.KuaDianVo;
import com.probox.common.entity.vo.statistics.ReconciliationVo;
import com.probox.common.log.annotation.Log;
import com.probox.common.log.enums.BusinessType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 财务统计
 */
@RestController
@RequestMapping("/finance")
public class FinanceController extends BaseController {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IPlatformStoreGroupService storeGroupService;

    @Autowired
    private IOrderRechargeService orderRechargeService;

    @Autowired
    private ICustomerFundStoreService fundStoreService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private StatisticsService statisticsService;

    /**
     * 查询订单列表
     */
    @GetMapping("/orderList")
    public TableDataInfo list(OrderInfo orderInfo) {
        if (orderInfo.getPayTimeArray() == null || orderInfo.getPayTimeArray().size()<2){
            List<OrderExport> list = new ArrayList<>();
            return getDataTable(list);
        }
        if(ObjectUtil.isEmpty(orderInfo.getStoreId())){
            orderInfo.setStoreId(SecurityUtils.getStoreId());
        }else{
            List<Long> stores = sysUserService.getUserStores(SecurityUtils.getUserId());
            if (stores != null) {
                if (orderInfo.getStoreIds() == null) {
                    orderInfo.setStoreIds(stores);
                } else {
                    orderInfo.getStoreIds().addAll(stores);
                }
            }
        }
        if (orderInfo.getStoreId() != null){
            if (orderInfo.getStoreIds() == null){
                orderInfo.setStoreIds(new ArrayList<>());
            }
            orderInfo.getStoreIds().add(orderInfo.getStoreId());
        }
        if (orderInfo.getStoreIds() == null || orderInfo.getStoreIds().size()==0){
            if (orderInfo.getStoreGroupId() != null){
                PlatformStoreGroup group = storeGroupService.getById(orderInfo.getStoreGroupId());
                if (group != null && StringUtils.isNotEmpty(group.getStoreIds())){
                    List<Long> ids = new ArrayList<>();
                    String[] storeIds = group.getStoreIds().split(",");
                    for(String s:storeIds){
                        if (StringUtils.isNotEmpty(s)){
                            ids.add(Long.parseLong(s));
                        }
                    }
                    if (ids.size()>0){
                        orderInfo.setStoreIds(ids);
                    }
                }
            }
        }
        startPage();
        TableDataInfo rst = orderInfoService.exportOrderDataInfo(orderInfo);
        List<OrderExport> list = (List<OrderExport>) rst.getRows();
        for (OrderExport o:list) {
            /*
            CustomerInfo ci = customerInfoService.getById(o.getCustomerUid());
            if (ci != null){
                o.setCustomerNo(ci.getCustomerNo());
                o.setContactName(ci.getContactMan());
            }*/
        }
        rst.setRows(list);
        return rst;
    }

    /**
     * 导出订单列表
     */
    @Log(title = "订单导出", businessType = BusinessType.EXPORT)
    @PostMapping("/orderExport")
    public void orderExport(HttpServletResponse response, OrderInfo orderInfo) throws IOException {
        if (orderInfo.getPayTimeArray() == null || orderInfo.getPayTimeArray().size()<2){
            List<OrderExport> list = new ArrayList<>();
            ExcelUtil<OrderExport> util = new ExcelUtil<OrderExport>(OrderExport.class);
            util.exportExcel(response, list, "订单报表");
        }else{
            if(ObjectUtil.isEmpty(orderInfo.getStoreId())){
                orderInfo.setStoreId(SecurityUtils.getStoreId());
            }else{
                List<Long> stores = sysUserService.getUserStores(SecurityUtils.getUserId());
                if (stores != null) {
                    if (orderInfo.getStoreIds() == null) {
                        orderInfo.setStoreIds(stores);
                    } else {
                        orderInfo.getStoreIds().addAll(stores);
                    }
                }
            }
            if (orderInfo.getStoreId() != null){
                if (orderInfo.getStoreIds() == null){
                    orderInfo.setStoreIds(new ArrayList<>());
                }
                orderInfo.getStoreIds().add(orderInfo.getStoreId());
            }
            if (orderInfo.getStoreIds() == null || orderInfo.getStoreIds().size()==0){
                if (orderInfo.getStoreGroupId() != null){
                    PlatformStoreGroup group = storeGroupService.getById(orderInfo.getStoreGroupId());
                    if (group != null && StringUtils.isNotEmpty(group.getStoreIds())){
                        List<Long> ids = new ArrayList<>();
                        String[] storeIds = group.getStoreIds().split(",");
                        for(String s:storeIds){
                            if (StringUtils.isNotEmpty(s)){
                                ids.add(Long.parseLong(s));
                            }
                        }
                        if (ids.size()>0){
                            orderInfo.setStoreIds(ids);
                        }
                    }
                }
            }
            List<OrderExport> list = orderInfoService.exportList(orderInfo);

            ExcelUtil<OrderExport> util = new ExcelUtil<OrderExport>(OrderExport.class);
            util.exportExcel(response, list, "订单报表");
        }
    }

    /**
     * 销售表查询
     */
    @GetMapping("/saleList")
    public TableDataInfo saleList(OrderInfo orderInfo) {
        if (orderInfo.getPayTimeArray() == null || orderInfo.getPayTimeArray().size()<2){
            List<OrderExport> list = new ArrayList<>();
            return getDataTable(list);
        }
        if(ObjectUtil.isEmpty(orderInfo.getStoreId())){
            orderInfo.setStoreId(SecurityUtils.getStoreId());
        }else{
            List<Long> stores = sysUserService.getUserStores(SecurityUtils.getUserId());
            if (stores != null) {
                if (orderInfo.getStoreIds() == null) {
                    orderInfo.setStoreIds(stores);
                } else {
                    orderInfo.getStoreIds().addAll(stores);
                }
            }
        }
        if (orderInfo.getStoreId() != null){
            if (orderInfo.getStoreIds() == null){
                orderInfo.setStoreIds(new ArrayList<>());
            }
            orderInfo.getStoreIds().add(orderInfo.getStoreId());
        }
        if (orderInfo.getStoreIds() == null || orderInfo.getStoreIds().size()==0){
            if (orderInfo.getStoreGroupId() != null){
                PlatformStoreGroup group = storeGroupService.getById(orderInfo.getStoreGroupId());
                if (group != null && StringUtils.isNotEmpty(group.getStoreIds())){
                    List<Long> ids = new ArrayList<>();
                    String[] storeIds = group.getStoreIds().split(",");
                    for(String s:storeIds){
                        if (StringUtils.isNotEmpty(s)){
                            ids.add(Long.parseLong(s));
                        }
                    }
                    if (ids.size()>0){
                        orderInfo.setStoreIds(ids);
                    }
                }
            }
        }
        startPage();
        TableDataInfo rst = orderInfoService.exportOrderDataInfo(orderInfo);
        List<OrderExport> list = (List<OrderExport>) rst.getRows();
        List<SaleExport> result = new ArrayList<>();
        for (OrderExport export:list){
            SaleExport se = new SaleExport();
            BeanUtils.copyProperties(export,se);
            result.add(se);
        }
        rst.setRows(result);
        return rst;
    }

    /**
     * 导出销售列表
     */
    @Log(title = "销售表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/saleExport")
    public void saleExport(HttpServletResponse response, OrderInfo orderInfo) throws IOException {
        if (orderInfo.getPayTimeArray() == null || orderInfo.getPayTimeArray().size()<2){
            List<SaleExport> list = new ArrayList<>();
            ExcelUtil<SaleExport> util = new ExcelUtil<SaleExport>(SaleExport.class);
            util.exportExcel(response, list, "销售报表");
        }else{
            if(ObjectUtil.isEmpty(orderInfo.getStoreId())){
                orderInfo.setStoreId(SecurityUtils.getStoreId());
            }else{
                List<Long> stores = sysUserService.getUserStores(SecurityUtils.getUserId());
                if (stores != null) {
                    if (orderInfo.getStoreIds() == null) {
                        orderInfo.setStoreIds(stores);
                    } else {
                        orderInfo.getStoreIds().addAll(stores);
                    }
                }
            }
            if (orderInfo.getStoreId() != null){
                if (orderInfo.getStoreIds() == null){
                    orderInfo.setStoreIds(new ArrayList<>());
                }
                orderInfo.getStoreIds().add(orderInfo.getStoreId());
            }
            if (orderInfo.getStoreIds() == null || orderInfo.getStoreIds().size()==0){
                if (orderInfo.getStoreGroupId() != null){
                    PlatformStoreGroup group = storeGroupService.getById(orderInfo.getStoreGroupId());
                    if (group != null && StringUtils.isNotEmpty(group.getStoreIds())){
                        List<Long> ids = new ArrayList<>();
                        String[] storeIds = group.getStoreIds().split(",");
                        for(String s:storeIds){
                            if (StringUtils.isNotEmpty(s)){
                                ids.add(Long.parseLong(s));
                            }
                        }
                        if (ids.size()>0){
                            orderInfo.setStoreIds(ids);
                        }
                    }
                }
            }
            List<OrderExport> list = orderInfoService.exportList(orderInfo);
            List<SaleExport> result = new ArrayList<>();
            for (OrderExport export:list){
                SaleExport se = new SaleExport();
                BeanUtils.copyProperties(export,se);
                result.add(se);
            }
            ExcelUtil<SaleExport> util = new ExcelUtil<SaleExport>(SaleExport.class);
            util.exportExcel(response, result, "订单报表");
        }
    }

    /**
     * 储值报表查询
     */
    @GetMapping("/rechargeList")
    public TableDataInfo rechargeList(OrderRecharge orderRecharge) {
        List<RechargeVo> rst =new ArrayList<RechargeVo>();
        List<OrderRecharge> list = new ArrayList<>();
        if (orderRecharge.getPayTimeArray() != null && orderRecharge.getPayTimeArray().size()>0){
            if(ObjectUtil.isEmpty(orderRecharge.getStoreId())){
                orderRecharge.setStoreId(SecurityUtils.getStoreId());
            }else{
                List<Long> stores = sysUserService.getUserStores(SecurityUtils.getUserId());
                if (stores != null) {
                    if (orderRecharge.getStoreIds() == null) {
                        orderRecharge.setStoreIds(stores);
                    } else {
                        orderRecharge.getStoreIds().addAll(stores);
                    }
                }
            }
            if (orderRecharge.getStoreId() != null){
                if (orderRecharge.getStoreIds() == null){
                    orderRecharge.setStoreIds(new ArrayList<>());
                }
                orderRecharge.getStoreIds().add(orderRecharge.getStoreId());
            }
            if (orderRecharge.getStoreIds() == null || orderRecharge.getStoreIds().size()==0){
                if (orderRecharge.getStoreGroupId() != null){
                    PlatformStoreGroup group = storeGroupService.getById(orderRecharge.getStoreGroupId());
                    if (group != null && StringUtils.isNotEmpty(group.getStoreIds())){
                        List<Long> ids = new ArrayList<>();
                        String[] storeIds = group.getStoreIds().split(",");
                        for(String s:storeIds){
                            if (StringUtils.isNotEmpty(s)){
                                ids.add(Long.parseLong(s));
                            }
                        }
                        if (ids.size()>0){
                            orderRecharge.setStoreIds(ids);
                        }
                    }
                }
            }
            startPage();
            list = orderRechargeService.queryList(orderRecharge);
            for (OrderRecharge r:list) {
                RechargeVo vo = new RechargeVo();
                BeanUtils.copyProperties(r,vo);
                rst.add(vo);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出充值订单列表
     */
    @Log(title = "充值订单导出", businessType = BusinessType.EXPORT)
    @PostMapping("/rechargeExport")
    public void rechargeExport(HttpServletResponse response, OrderRecharge orderRecharge) throws IOException {
        List<RechargeVo> rst =new ArrayList<RechargeVo>();
        if (orderRecharge.getPayTimeArray() != null && orderRecharge.getPayTimeArray().size()>0){
            if(ObjectUtil.isEmpty(orderRecharge.getStoreId())){
                orderRecharge.setStoreId(SecurityUtils.getStoreId());
            }else{
                List<Long> stores = sysUserService.getUserStores(SecurityUtils.getUserId());
                if (stores != null) {
                    if (orderRecharge.getStoreIds() == null) {
                        orderRecharge.setStoreIds(stores);
                    } else {
                        orderRecharge.getStoreIds().addAll(stores);
                    }
                }
            }
            if (orderRecharge.getStoreId() != null){
                if (orderRecharge.getStoreIds() == null){
                    orderRecharge.setStoreIds(new ArrayList<>());
                }
                orderRecharge.getStoreIds().add(orderRecharge.getStoreId());
            }
            if (orderRecharge.getStoreIds() == null || orderRecharge.getStoreIds().size()==0){
                if (orderRecharge.getStoreGroupId() != null){
                    PlatformStoreGroup group = storeGroupService.getById(orderRecharge.getStoreGroupId());
                    if (group != null && StringUtils.isNotEmpty(group.getStoreIds())){
                        List<Long> ids = new ArrayList<>();
                        String[] storeIds = group.getStoreIds().split(",");
                        for(String s:storeIds){
                            if (StringUtils.isNotEmpty(s)){
                                ids.add(Long.parseLong(s));
                            }
                        }
                        if (ids.size()>0){
                            orderRecharge.setStoreIds(ids);
                        }
                    }
                }
            }
            List<OrderRecharge> list = orderRechargeService.queryList(orderRecharge);
            for (OrderRecharge r:list) {
                RechargeVo vo = new RechargeVo();
                BeanUtils.copyProperties(r,vo);
                vo.setOrderAmountStr(vo.getOrderAmountStr());
                vo.setOrderStatusStr(vo.getOrderStatusStr());
                vo.setPayAmountStr(vo.getPayAmountStr());
                vo.setPayMethodStr(vo.getPayMethodStr());
                vo.setPayStatusStr(vo.getPayStatusStr());
                vo.setPlatSourceStr(vo.getPlatSourceStr());
                rst.add(vo);
            }
        }

        ExcelUtil<RechargeVo> util = new ExcelUtil<RechargeVo>(RechargeVo.class);
        util.exportExcel(response, rst, "充值表");
    }

    /**
     * 门店负债报表查询
     */
    @GetMapping("/storeFundList")
    public TableDataInfo storeFundList() {
        Long storeId = SecurityUtils.getStoreId();
        return getDataTable(fundStoreService.sumStoreFundList(storeId));
    }

    /**
     * 门店负债报表明细
     */
    @GetMapping("/storeFundDetail/{storeId}")
    public TableDataInfo storeFundDetail(@PathVariable Long storeId) {
        startPage();
        return getDataTable(fundStoreService.customerStoreFundList(storeId));
    }




    /**
     * 跨店查询
     */
    @GetMapping("/kuaList")
    public AjaxResult kuaList(ReconciliationVo vo) {

        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(vo.getStartTime()) || StringUtils.isEmpty(vo.getEndTime()) || vo.getStoreId() == null){
            List<ReconciliationVo> reconciliationVos = new ArrayList<>();
            ajaxResult.put("rows", reconciliationVos);
            ajaxResult.put("manCount", 0L);
            ajaxResult.put("itemCount", 0L);
            ajaxResult.put("kuaDianShouRu", 0L);
            ajaxResult.put("kuaDianZhiChu", 0L);
            ajaxResult.put("code", HttpStatus.SUCCESS);
            ajaxResult.put("msg", "查询成功");
            ajaxResult.put("total",0L);
        }else{
            startPage();
            List<KuaDianVo> reconciliationVos = statisticsService.selectKuaDianList(vo);
            ajaxResult.put("rows", reconciliationVos);
            ajaxResult.put("manCount", statisticsService.selectReconciliationVoManCount(vo).getManCount());
            ajaxResult.put("itemCount", statisticsService.selectReconciliationVoItemCount(vo).getServiceAmount());
            vo.setCountType("1");
            ajaxResult.put("kuaDianShouRu", statisticsService.selectReconciliationVoKuaDianShouRuAndZhiChu(vo).getKuaDian());

            //Long payStoreId = vo.getPayStoreId();
            //vo.setPayStoreId(vo.getStoreId());
            //vo.setStoreId(payStoreId);
            vo.setCountType("2");
            ajaxResult.put("kuaDianZhiChu", statisticsService.selectReconciliationVoKuaDianShouRuAndZhiChu(vo).getKuaDian());
            ajaxResult.put("code", HttpStatus.SUCCESS);
            ajaxResult.put("msg", "查询成功");
            ajaxResult.put("total", new PageInfo(reconciliationVos).getTotal());
        }
        return ajaxResult;
    }

    /**
     * 导出充值订单列表
     */
    @Log(title = "跨店明细导出", businessType = BusinessType.EXPORT)
    @PostMapping("/kuaExport")
    public void kuaExport(HttpServletResponse response, ReconciliationVo vo) throws IOException {
        List<KuaDianVo> reconciliationVos = new ArrayList<>();
        if (StringUtils.isEmpty(vo.getStartTime()) || StringUtils.isEmpty(vo.getEndTime()) || vo.getStoreId() == null){
        }else{
            reconciliationVos = statisticsService.selectKuaDianList(vo);
            for (KuaDianVo kd:reconciliationVos) {
                kd.setCollectionPriceStr(kd.getCollectionPriceStr());
                kd.setCostPriceStr(kd.getCostPriceStr());
                kd.setPayGoldCoinStr(kd.getPayGoldCoinStr());
                kd.setPaySilverCoinStr(kd.getPaySilverCoinStr());
                kd.setSourcePlatformStr(kd.getSourcePlatformStr());
                kd.setSettlementPriceStr(kd.getSettlementPriceStr());
            }
        }
        ExcelUtil<KuaDianVo> util = new ExcelUtil<KuaDianVo>(KuaDianVo.class);
        util.exportExcel(response, reconciliationVos, "跨店明细");
    }

    /**
     * 导出门店负债报表明细
     */
    @PostMapping("/storeFundDetailExport/{storeId}")
    public void storeFundDetailExport(HttpServletResponse response,@PathVariable Long storeId) throws IOException{
        ExcelUtil<CustomerFundStore> util = new ExcelUtil<CustomerFundStore>(CustomerFundStore.class);
        util.exportExcel(response, fundStoreService.customerStoreFundList(storeId), "门店负债明细");
    }

}
